/**
 * Writed by yura and mak
 */

package wz.legend.handlers;

import java.io.InputStream;
import java.util.List;

import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.Status;
import wz.legend.handlers.steps.Step;
import wz.legend.handlers.steps.StepLoader;
import wz.legend.handlers.steps.StepMachine;
import wz.legend.handlers.steps.StepMachineImpl;


public class WalkingHandler implements ResponseHandler {
    private static final Logger LOG = Logger
            .getLogger(WalkingHandler.class);

    private StepMachine stepMachine = null;
    private String stepsFileName = null;
    private long stepsTimeout = 5000;

    private void init() {
        InputStream stream = WalkingHandler.class.getClassLoader()
                .getResourceAsStream(stepsFileName);
        List<Step> steps = StepLoader.loadSteps(stream);
        stepMachine = new StepMachineImpl(steps);
        stepMachine.setTimeoutStepStart(stepsTimeout);
    }

    public void handle(HttpContext httpContext, Context context) {
        try {
            if (context.getStatus() == Status.WALKING) {
                if (stepMachine == null) {
                    init();
                }
                if (!stepMachine.isDone()) {
                    stepMachine.handle(httpContext, context);
                } else {
                    LOG.debug("All steps done");
                    context.setStatus(Status.INACTIVE);
                }
            } else {
                if (stepMachine != null) {
                    stepMachine.reset();
                }
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }

    }

    public String getStepsFileName() {
        return stepsFileName;
    }

    public void setStepsFileName(String stepsFileName) {
        this.stepsFileName = stepsFileName;
    }

    public long getStepsTimeout() {
        return stepsTimeout;
    }

    public void setStepsTimeout(long stepsTimeout) {
        this.stepsTimeout = stepsTimeout;
    }

    public StepMachine getStepMachine() {
        return stepMachine;
    }

    public void setStepMachine(StepMachine stepMachine) {
        this.stepMachine = stepMachine;
    }
}
